package com.zzy.lean_mqtt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttReceiverConfig {

    @Value("${mqtt.broker-url}")
    private String brokerUrl;

    @Value("${mqtt.client-id}")
    private String clientId;

    @Autowired
    private MqttPahoClientFactory mqttClientFactory;

    // 1. 创建入站消息通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    // 2. 创建 MQTT 入站通道适配器（订阅者）
    @Bean
    public MqttPahoMessageDrivenChannelAdapter mqttInbound() {
        // 注意：入站客户端的 ID 必须唯一，不能和出站客户端重复
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId + "_in", mqttClientFactory, "test/topic", "another/topic"); // 可以订阅多个主题
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    // 3. 创建消息处理器，处理接收到的消息
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String topic = (String) message.getHeaders().get("mqtt_receivedTopic");
            String payload = (String) message.getPayload();
            System.out.println("收到消息 -> 主题: " + topic + ", 内容: " + payload);
        };
    }
}